﻿using AForge.Video;
using AForge.Video.DirectShow;
using System;
using System.Threading.Tasks;

namespace Clancy.Bl.VideoProvider
{
    internal class CaptureDeviceVideoSource : VideoSourceBase
    {
        private VideoCaptureDevice m_VideoCaptureDevice;

        public CaptureDeviceVideoSource(string monikerString)
            : base(monikerString)
        {
        }

        protected override Task<bool> DoClose()
        {
            if (m_VideoCaptureDevice == null)
                return Task.FromResult(false);

            m_VideoCaptureDevice.Stop();
            return Task.FromResult(true);
        }

        protected override Task<bool> DoOpenVideoCapture(string monikerString)
        {
            m_VideoCaptureDevice = new VideoCaptureDevice(monikerString);
            m_VideoCaptureDevice.NewFrame += OnVideoCaptureDeviceOnNewFrame;
            m_VideoCaptureDevice.Start();
            return Task.FromResult(m_VideoCaptureDevice.IsRunning);
        }

        protected override void DoShowSettingsDialog()
        {
            if (m_VideoCaptureDevice == null)
                return;

            try
            {
                m_VideoCaptureDevice.DisplayPropertyPage(IntPtr.Zero);
            }
            catch { }
        }

        private void OnVideoCaptureDeviceOnNewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            if (eventArgs == null)
                return;

            IncomingFrame.OnNext(eventArgs.Frame);

            eventArgs.Frame.Dispose();
        }
    }
}